package com.supermarket.controller;

import com.supermarket.entity.DTO.LoginLogDTO;
import com.supermarket.entity.LoginLog;
import com.supermarket.service.LoginLogService;
import com.supermarket.common.ResponseResult;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/loginlog")
public class LoginLogController {

    @Resource
    private LoginLogService loginLogService;

    /**
     * 新增登录日志
     *
     * @param loginLog 登录日志对象
     * @return 包含操作结果的响应结果
     */
    @PostMapping("/add")
    public ResponseResult<String> addLoginLog(@RequestBody LoginLog loginLog) {
        int result = loginLogService.addLoginLog(loginLog.getId(), loginLog.getLoginIp(), loginLog.getStatus());
        if (result > 0) {
            return ResponseResult.success("登录日志添加成功");
        } else {
            return ResponseResult.error(400, "登录日志添加失败");
        }
    }

    /**
     * 查询所有登录日志
     *
     * @return 包含所有登录日志的响应结果
     */
    @GetMapping("/all")
    public ResponseResult<List<LoginLogDTO>> getAllLoginLogs() {
        List<LoginLogDTO> loginLogs = loginLogService.getAllLoginLogs();
        return ResponseResult.success(loginLogs);
    }

    /**
     * 分页查询所有登录日志
     *
     * @param pageNum  当前页码
     * @param pageSize 每页显示条数
     * @return 包含分页结果的响应结果
     *         返回的数据结构如下：
     *         {
     *             "list": [
     *                 {
     *                     "id": 登录日志ID,
     *                     "userId": 用户ID,
     *                     "loginTime": 登录时间,
     *                     "loginIp": 登录IP,
     *                     "status": 状态,
     *                     "username": 用户账号,
     *                     "nickname": 用户昵称
     *                 }
     *             ],
     *             "total": 总记录数,
     *             "pageNum": 当前页码,
     *             "pageSize": 每页显示条数,
     *             "pages": 总页数
     *         }
     */
    @GetMapping("/all/page")
    public ResponseResult<Map<String, Object>> getAllLoginLogsByPage(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        Map<String, Object> result = loginLogService.getAllLoginLogsByPage(pageNum, pageSize);
        return ResponseResult.success(result);
    }

    /**
     * 根据ID删除登录日志
     *
     * @param id 登录日志ID
     * @return 包含操作结果的响应结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseResult<String> deleteLoginLogById(@PathVariable Integer id) {
        int result = loginLogService.deleteLoginLogById(id);
        if (result > 0) {
            return ResponseResult.success("登录日志删除成功");
        } else {
            return ResponseResult.error(400, "登录日志删除失败");
        }
    }
}